<template>
	<view class="container">
		<view id="baidu-map" class="map"></view>
		<view class="tip">点击地图任意位置即可选点</view>
	</view>
</template>

<script>
export default {
	data(){
		return {
			ak: 'H4YdFbkDBIbCvaNBsbrFRSlvxEjCHCvC',
			map: null,
			geocoder: null
		}
	},
	onLoad(){
		this.loadBaiduMapScript().then(() => {
			this.initMap();
		});
	},
	methods: {
		loadBaiduMapScript(){
			return new Promise((resolve) => {
				if (typeof window !== 'undefined' && window.BMapGL) {
					resolve();
					return;
				}
				// 兼容 Baidu 脚本内部使用 document.write 的情况：暂时重写为安全插入
				const originalWrite = document.write.bind(document);
				document.write = (html) => {
					try {
						if (html && html.indexOf('<script') > -1) {
							const srcMatch = html.match(/src=["']([^"']+)["']/i);
							if (srcMatch && srcMatch[1]) {
								const s = document.createElement('script');
								s.type = 'text/javascript';
								s.src = srcMatch[1];
								document.head.appendChild(s);
							}
							return;
						}
						if (html && html.indexOf('<link') > -1) {
							const hrefMatch = html.match(/href=["']([^"']+)["']/i);
							if (hrefMatch && hrefMatch[1]) {
								const l = document.createElement('link');
								l.rel = 'stylesheet';
								l.type = 'text/css';
								l.href = hrefMatch[1];
								document.head.appendChild(l);
							}
							return;
						}
					} catch (e) {
						// 回退到原始写入（通常不会走到）
						originalWrite(html);
					}
				};
				const script = document.createElement('script');
				script.type = 'text/javascript';
				script.src = `https://api.map.baidu.com/api?v=1.0&type=webgl&ak=${this.ak}`;
				// 等待 BMapGL 就绪后恢复 document.write 并 resolve
				const finishWhenReady = () => {
					if (window && window.BMapGL && window.BMapGL.Map) {
						document.write = originalWrite;
						resolve();
						return;
					}
					setTimeout(finishWhenReady, 50);
				};
				script.onload = finishWhenReady;
				document.head.appendChild(script);
			});
		},
		initMap(){
			if (!(window && window.BMapGL)) return;
			this.map = new window.BMapGL.Map('baidu-map');
			this.geocoder = new window.BMapGL.Geocoder();
			const defaultPoint = new window.BMapGL.Point(113.657804, 34.727476);
			this.map.centerAndZoom(defaultPoint, 15);
			this.map.enableScrollWheelZoom(true);
			try {
				const geo = new window.BMapGL.Geolocation();
				geo.getCurrentPosition((r) => {
					if (this.geoAllowed(r)) {
						this.map.centerAndZoom(r.point, 16);
					}
				});
			} catch(e) {}
			this.map.addEventListener('click', (e) => {
				const point = e.latlng || e.point; // BMapGL 事件为 latlng
				this.map.clearOverlays();
				this.map.addOverlay(new window.BMapGL.Marker(point));
				this.geocoder.getLocation(point, (rs) => {
					const c = rs && rs.addressComponents ? rs.addressComponents : {};
					const full = `${c.province || ''}${c.city || ''}${c.district || ''}${c.street || ''}${c.streetNumber || ''}`;
					const result = {
						name: full || '已选择位置',
						address: full,
						lng: point.lng,
						lat: point.lat,
						province: c.province || '',
						city: c.city || '',
						area: c.district || '',
						street: c.street || '',
						streetNumber: c.streetNumber || '',
						town: c.town || '',
						adcode: (c.adcode || c.adCode || '')
					};
					const channel = this.getOpenerEventChannel && this.getOpenerEventChannel();
					channel && channel.emit('h5LocationPicked', result);
					uni.navigateBack();
				});
			});
		},
		geoAllowed(r){
			return r && (r.accuracy || r.address || r.point);
		}
	}
}
</script>

<style lang="scss">
.container{
	position: fixed;
	top: 0; left: 0; right: 0; bottom: 0;
	background: #fff;
}
.map{
	position: absolute;
	top: 0; left: 0; right: 0; bottom: 60upx;
}
.tip{
	position: absolute;
	left: 0; right: 0; bottom: 0;
	padding: 12upx 24upx;
	text-align: center;
	font-size: 26upx;
	color: #666;
	background: #fafafa;
	border-top: 1px solid #eee;
}
</style>


